<script setup lang="ts">
import { ref, reactive } from 'vue';
import draggable from 'vuedraggable';

type List = Record<string, string | number>;

// 用 reactive 定义拖拽结束后不会保持拖拽后的位置，而会恢复到初始位置，只有 ref 定义的时候才能拖拽并排序

// let gridLists = reactive<List[]>([
//   { grid: 'cn', num: 1 },
//   { grid: 'cn', num: 2 },
//   { grid: 'cn', num: 3 },
//   { grid: 'cn', num: 4 },
//   { grid: 'cn', num: 5 },
//   { grid: 'cn', num: 6 },
//   { grid: 'cn', num: 7 },
//   { grid: 'cn', num: 8 },
//   { grid: 'cn', num: 9 },
// ]);

let gridLists = ref<List[]>([
  { grid: 'grid1', num: 1 },
  { grid: 'grid2', num: 2 },
  { grid: 'grid3', num: 3 },
  { grid: 'grid4', num: 4 },
  { grid: 'grid5', num: 5 },
  { grid: 'grid6', num: 6 },
  { grid: 'grid7', num: 7 },
  { grid: 'grid8', num: 8 },
  { grid: 'grid9', num: 9 },
]);
</script>

<template>
  <div class="p-4 h-full">
    <div class="wrap">
      <div class="title">宫格拖拽排序（本页面已KeepAlive）</div>
      <div>
        <el-row>
          <el-col :xs="0" :sm="0" :md="0" :lg="8"></el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8">
            <draggable
              v-model="gridLists"
              class="grid-container"
              item-key="grid"
              animation="300"
              chosenClass="chosen"
              forceFallback="true"
            >
              <template #item="{ element }">
                <div :class="'item' + ' ' + 'item-' + element.num">
                  {{ element.num }}
                </div>
              </template>
            </draggable>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.wrap {
  border: 1px solid #e6e8eb;
  background-color: #ffffff;
  .title {
    font-weight: bold;
    padding: 20px;
    border-bottom: 1px solid #e6e8eb;
    box-sizing: border-box;
  }

  & > :last-child {
    padding: 20px;
    box-sizing: border-box;
  }
}
.grid-container {
  display: grid;
  grid-template-columns: 33.3% 33.3% 33.3%;
  grid-template-rows: 33.3% 33.3% 33.3%;
}
.item {
  font-size: 2em;
  text-align: center;
  line-height: 100px;
  border: 1px solid #e5e4e9;
  cursor: move;
  @media screen and (max-width: 750px) {
    line-height: 90px;
  }
}
.item-1 {
  background-color: #e6e6fa;
}

.item-2 {
  background-color: #cdba96;
}

.item-3 {
  background-color: #87cefa;
}

.item-4 {
  background-color: #90ee90;
}

.item-5 {
  background-color: #c077af;
}

.item-6 {
  background-color: #f8d29d;
}

.item-7 {
  background-color: #ff6347;
}

.item-8 {
  background-color: #d0e4a9;
}

.item-9 {
  background-color: #ffa500;
}

.chosen {
  border: solid 2px #3089dc !important;
}
</style>
